'''
curl -X POST 'https://api.coze.cn/v3/chat?' \
-H "Authorization: Bearer cztei_lmNN3bNxgeHYFNBU8HjteXWLWEA2FseuFyjjNrXxXc4kfgscpFbvVy5mKDRWhtJUI" \
-H "Content-Type: application/json" \
-d '{
  "bot_id": "7537124389670780991",
  "user_id": "123456789",
  "stream": true,
  "additional_messages": [
    {
      "content": "hello",
      "content_type": "text",
      "role": "user",
      "type": "question"
    }
  ],
  "parameters": {}
}'
'''

import requests
import json

url = "https://api.coze.cn/v3/chat?"
headers = {
    "Authorization": "Bearer cztei_lmNN3bNxgeHYFNBU8HjteXWLWEA2FseuFyjjNrXxXc4kfgscpFbvVy5mKDRWhtJUI",
    "Content-Type": "application/json"
}
data = {
    "bot_id": "7537124389670780991",
    "user_id": "123456789",
    "stream": True,
    "additional_messages": [
        {
            "content": "hello",
            "content_type": "text",
            "role": "user",
            "type": "question"
        }
    ],
    "parameters": {}
}

# 启用流式响应
response = requests.post(url, headers=headers, json=data, stream=True)

# 打印响应状态码
print(f"Status Code: {response.status_code}")

# 处理流式响应
if response.status_code == 200:
    for line in response.iter_lines(decode_unicode=True):
        if line:
            # 移除SSE前缀 "data:"
            if line.startswith("data:"):
                line = line[5:].strip()
                try:
                    # 解析JSON数据
                    data = json.loads(line)
                    # 提取并打印回复内容
                    if "messages" in data and len(data["messages"]) > 0:
                        content = data["messages"][0].get("content", "")
                        print(content, end="", flush=True)
                except json.JSONDecodeError:
                    # 非JSON行直接打印
                    print(line, end="", flush=True)
else:
    print("Error:", response.text)